require("./index.scss");
var Pagination = require("COMMON/modules/pagination-x/v1.0");
var ParseTemplate = ZFT.Util.ParseTemplate;
var Ajax = ZFT.Util.Ajax;
var cData = require("COMMON/js/config.province.city.data");
var Template = {
    cntbox: ParseTemplate(require("./tpl/cntbox.xtpl")),
    gathercntbox: ParseTemplate(require("./tpl/gathercntbox.xtpl")),
    paycntbox: ParseTemplate(require("./tpl/paycntbox.xtpl")),
    paylist: ParseTemplate(require("./tpl/paylist.xtpl")),
    gatherlist: ParseTemplate(require("./tpl/gatherlist.xtpl")),
    tr: ParseTemplate(require("./tpl/tr.xtpl"))
}
var Main = ZFT.Util.Class({
    container: $("body"),
    init: function () {
        var _this = this;
        _this.getBuildCnt(); //获取头部楼宇房源数据
        _this.getBuildingList();
        var pagination = this.pagination = new Pagination({
            container: $(".paginationWrap"),
            count: 5,
            showTotal: true,
            jump: true,
            filter: true
        });
        var paginationPay = this.paginationPay = new Pagination({
            container: $(".paginationWrapPay"),
            count: 5,
            showTotal: true,
            jump: true,
            filter: true
        });
        pagination.on("page.switch", function (toPage, currentPage, totalPage) {
            pagination.render({ current: currentPage, toPage: toPage }),
                _this.getGatherList(toPage);
        });

        paginationPay.on("page.switch", function (toPage, currentPage, totalPage) {
            paginationPay.render({ current: currentPage, toPage: toPage }),
                _this.getPaymentList(toPage);
        });


    },
    EVENTS: {
        "click #headTab .m-head_tab_title": "switchTab",
        "change .schInp": "changeGather",
        "click #expBtn": "onExpBtnClick"
    },
    //切换tab页
    switchTab: function (e) {
        var _this = $(e.currentTarget);
        var gather = $("#gather"),
            pay = $("#pay");
        if (_this.hasClass("gather", "noactive")) {
            _this.removeClass("noactive").siblings().addClass("noactive");
            gather.fadeIn(200).show();
            pay.fadeIn(200).hide();
        } else if (_this.hasClass("pay", "noactive")) {
            _this.removeClass("noactive").siblings().addClass("noactive");
            gather.fadeIn(200).hide();
            pay.fadeIn(200).show();
        }
    },
    //切换日期时触发查询收款以及付款列表的请求
    changeGather: function (e) {
        var _this = this;
        var tarBtn = $(e.currentTarget);
        var id = tarBtn.attr("id");
        if (id == "schGather") {
            _this.getGatherList(1);
        } else if (id == "schPay") {
            _this.getPaymentList(1);
        }
    },
    getBuildCnt: function () {
        var _this = this;
        Ajax("/r/Building_incomeBuildSummary", {
            type: "POST",
            dataType: "json",
            success: function (res) {
                var dtype = ZFT.Util.getDtype();
                if (res.code == 200) {
                    if (dtype == 0 || dtype == 1 || dtype == 2 || dtype == 5 || dtype == 6) {
                        $("#tabPay").hide();
                        _this.initDatepicker(0);
                    } else {
                        _this.initDatepicker(1);
                    }
                    var html = Template.cntbox(res.data);
                    $("#cntBox").html(html);
                    //   console.log(res.data.dtype)
                } else {
                    ZFT.Util.STip("fail", res.msg, 4000);
                }
            }
        })
    },
    //初始化日历插件
    initDatepicker: function (ifSch) {
        var year = new Date().getFullYear();
        var m = new Date().getMonth() + 1 + "";
        var month = (m.length <= 1) ? "0" + m : m;
        var ym = year + month;
        if (ifSch == 0) {
            $("#schGather").val(ym);
        } else if (ifSch == 1) {
            $("#schGather,#schPay").val(ym);
        }
        // console.log(ym)
        $("#schGather").datepicker({
            format: "yyyymm",
            maxViewMode: 2,
            minViewMode: "months",
            language: "zh-CN",
            autoclose: true,
        });
        $('#schPay').datepicker({
            format: "yyyymm",
            maxViewMode: 2,
            minViewMode: "months",
            language: "zh-CN",
            autoclose: true
        });
    },

    //获取收款统计
    getGatherCnt: function (time) {
        var gatherCntBox = $("#gatherCntBox");
        var dtype = ZFT.Util.getDtype();
        var data = {
            count: 0,
            count_payed: 0,
            count_unpayed: 0,
            total_money: 0,
            payed_money: 0,
            dtype: dtype,
            unpayed_money: 0,
        }
        Ajax("/r/BillManager_incomeManagerSummary", {
            type: "POST",
            dataType: "json",
            params: {
                time: time ? time : 0,
                building_id: $("#gatherBuildId").val()
            },
            success: function (res) {
                var resdata = res.data;
                if (res.code == 200) {
                    var html;
                    resdata["dtype"] = dtype;
                    //console.log(resdata);
                    html = Template.gathercntbox(resdata);
                    gatherCntBox.html(html);
                } else if (res.code == 201) {
                    var html = Template.gathercntbox(data);
                    gatherCntBox.html(html);
                } else {
                    gatherCntBox.html("");
                    return ZFT.Util.STip("fail", res.msg, 4000);
                }

            }
        })
    },
    getGatherList: function (toPage) {
        var _this = this;
        var tbody = $("#tbody");
        var page = $(".paginationWrap");
        var page_size = page.attr("data-size");
        var building_id = $("#gatherBuildId").val();
        var time = $("#schGather").val()
        var param = {
            time: time,
            building_id: building_id,
            page: toPage ? toPage : 1,
            page_size: page_size ? page_size : 10,
            excel: 0
        };
        _this.getGatherCnt(time);
        Ajax("/r/BillManager_incomeManager", {
            type: "POST",
            dataType: "json",
            params: param,
            loading: function () {
                var html = '<tr><td colspan="12">加载中,请稍后...</td></tr>';
                tbody.html(html);
                page.hide();
            },
            success: function (res) {
                if (res.code == 200) {
                    var html = Template.gatherlist({ data: res.data.list });
                    tbody.html(html);
                    _this.pagination.render({ current: toPage, toPage: toPage, total: res.data.total })
                } else if (res.code == 102) {
                    var relogin = '<tr><td colspan="12"><a href="index/logOut">未登录,请重新登录</a></td></tr>'
                    tbody.html(relogin);
                } else if (res.code == 201) {
                    var html = '<tr><td colspan="12">' + res.msg + '</td></tr>'
                    tbody.html(html);
                }
            }
        })
    },
    onExpBtnClick: function () {
        var _this = this;
        var param = {
            time: $("#schGather").val(),
            excel: 0
        };
        Ajax("/r/BillManager_incomeManager", {
            type: "POST",
            dataType: "json",
            params: param,
            success: function (res) {
                if (res.code == 200) {
                    window.open('/r/BillManager_incomeManager?time=' + param["time"] + '&excel=1', '_self');
                } else {
                    return ZFT.Util.STip("fail", res.msg, 3000);
                }
            }
        })
    },
    getPaymentCnt: function (time) {
        var payCntBox = $("#payCntBox");
        var data = {
            rent_count: 0,
            should_get: 0,
            real_count: 0,
            real_get: 0,
            pay_count: 0,
            pay_money: 0,
            real_pay_count: 0,
            real_pay_money: 0,
            overdue_count: 0,
            overdue_money: 0,
        }
        Ajax("/r/BillManager_incomePaySummary", {
            type: "POST",
            dataType: "json",
            params: {
                time: time,
                building_id: $("#payBuildId").val()
            },
            success: function (res) {
                if (res.code == 200) {
                    var html = Template.paycntbox(res.data);
                    payCntBox.html(html);
                } else if (res.code == 201) {
                    var html = Template.paycntbox(data);
                    payCntBox.html(html);
                } else {
                    payCntBox.html("");
                    return ZFT.Util.STip("fail", res.msg, 4000);
                }

            }
        })
    },
    getPaymentList: function (toPage) {
        var _this = this;
        var tbody = $("#tbodyPay");
        var page = $(".paginationWrapPay");
        var building_id = $("#payBuildId").val();
        var page_size = page.attr("data-size");
        var time = $("#schPay").val()
        var param = {
            time: time,
            building_id: building_id,
            page: toPage ? toPage : 1,
            page_size: page_size ? page_size : 10,
        };
        if (!time) return false;
        _this.getPaymentCnt(time);
        Ajax("/r/BillManager_payManager", {
            type: "POST",
            dataType: "json",
            params: param,
            loading: function () {
                var html = '<tr><td colspan="11">加载中,请稍后...</td></tr>';
                tbody.html(html);
                page.hide();
            },
            success: function (res) {
                var list = res.data.list;
                if (res.code == 200) {
                    if (list) {
                        for (var i = 0, len = list.length; i < len; i++) {
                            var item = list[i];
                            var prov = item.province;
                            var city = item.city;
                            var area = _this.getLocationName(prov, city);
                            item["city_area"] = area;
                        }
                        var html = Template.paylist({ data: res.data.list });
                        tbody.html(html);
                        // (res.data.total > 1) ? _this.Pagination.render({ current: toPage, toPage: toPage, total: res.data.total }) : "";
                        _this.paginationPay.render({ current: toPage, toPage: toPage, total: res.data.total });
                    } else {
                        return tbody.html('<tr><td colspan="11">暂无数据</td></tr>');
                    }


                } else if (res.code == 102) {
                    var relogin = '<tr><td colspan="11"><a href="index/logOut">未登录,请重新登录</a></td></tr>'
                    tbody.html(relogin);
                } else if (res.code == 201) {
                    var html = '<tr><td colspan="11">' + res.msg + '</td></tr>'
                    tbody.html(html);
                }
            }
        })
    },
    //通过区域码获取对应名称
    getLocationName: function (prov, cityId) {
        var province = cData[prov];
        var prov_name = province.name;
        var citys = province.city;
        var city_name = "";
        for (var i = 0; i < citys.length; i++) {
            var city = citys[i];
            var city_id = city.id;
            if (city_id == cityId) {
                city_name = city.name;
                break;
            }
        }
        return prov_name + " " + city_name;
    },

    getBuildingList: function () {
        var _this = this;
        Ajax("/r/Building_getOwnerBuilding", {
            "type": "POST",
            "dataType": "json",
            success: function (res) {
                if (res.code == 200) {
                    var html,
                        data = res.data;
                    data["approvePer"] = ($.inArray("29", _this.pers) !== -1) ? 1 : 0;
                    html = Template.tr({ data: data });
                    $(".buildingId").html(html);
                    _this.toggleBuilding();
                } else {
                    STip("fail", res.msg);
                }
            }
        })
    },
    toggleBuilding: function () {
        var _this = this;
        $(".buildingId").on("change", function (e) {
            var tarBtn = $(e.currentTarget),
                type = tarBtn.attr("data-type");
            (type === "pay") ? 　_this.getPaymentList(1) : _this.getGatherList(1);
        })
    }

});
$(function () {
    new Main();
})